package com.laoxu.java.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.laoxu.java.common.Result;
import com.laoxu.java.common.ResultUtil;
import com.laoxu.java.entity.User;
import com.laoxu.java.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/user")
public class UserController {
    @Autowired
    private UserService userService;

    @GetMapping("/list")
    public Result<IPage<User>> list(@RequestParam(required = false) String query,
                                    @RequestParam(defaultValue = "1") Integer pageNo,
                                    @RequestParam(defaultValue = "10") Integer pageSize) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        if(!StringUtils.isEmpty(query)){
            queryWrapper.like("username",query);
        }

        Page<User> page = new Page<>(pageNo,pageSize);

        IPage<User> pageResult = userService.page(page, queryWrapper);

        // 设置总记录数
        pageResult.setTotal(userService.count(queryWrapper));

        return ResultUtil.ok(pageResult);
    }

    @PostMapping("/removes")
    public Result<String> remove(@RequestBody List<Integer> ids){
        userService.removeByIds(ids);
        return ResultUtil.ok();
    }

    @PostMapping("/remove/{id}")
    public Result<String> remove(@PathVariable Integer id){
        userService.removeById(id);
        return ResultUtil.ok();
    }

    @PostMapping("/modify")
    public Result<String> save(@RequestBody User entity){
        userService.saveOrUpdate(entity);
        return ResultUtil.ok();
    }

    @GetMapping("/{id}")
    public Result<User> get(@PathVariable Integer id){
        return ResultUtil.ok(userService.getById(id));
    }



}
